package com.itheima.web.controller.store;


import com.github.pagehelper.PageInfo;
import com.itheima.domain.store.Company;
import com.itheima.utils.BeanUtil;
import com.itheima.web.BaseServlet.BaseServlet;

import org.apache.commons.lang3.StringUtils;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/store/company")
public class CompanyServlet extends BaseServlet {
    /**
     * 分页查询
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String page = req.getParameter("page");
        String size = req.getParameter("size");

        PageInfo<Company> all = companyService.findAll(page, size);
        //将数据保存到请求域中
        req.setAttribute("page", all);
        req.getRequestDispatcher("/WEB-INF/pages/store/company/list.jsp").forward(req, resp);
    }

    /**
     * 跳转到添加信息的界面
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //跳转页面
        req.getRequestDispatcher("/WEB-INF/pages/store/company/add.jsp").forward(req, resp);
    }

    /**
     * 添加信息的方法
     *
     * @param req
     * @param resp
     * @throws IOException
     */
    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Company company = BeanUtil.fillBean(req, Company.class, "yyyy-MM-dd");
        //调用业务层接口save;
        companyService.save(company);
        resp.sendRedirect(req.getContextPath() + "/store/company?operation=list");
    }

    /**
     * 跳转到修改界面
     *
     * @param req
     * @param resp
     */
    public void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //查询要修改的数据id
        String id = req.getParameter("id");
        Company company = companyService.findById(id);
        //将数据加载到请求域中,供页面获取
        req.setAttribute("company",company);
        req.getRequestDispatcher("/WEB-INF/pages/store/company/update.jsp").forward(req,resp);
    }

    public void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        Company company = BeanUtil.fillBean(req, Company.class, "yyyy-MM-dd");
        companyService.update(company);
        //修改完毕,重定向到分页查询页面
        resp.sendRedirect(req.getContextPath()+"/store/company?operation=list");
    }
    public void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String id = req.getParameter("id");
        companyService.delete(id);
        //删除完毕,重定向到分页查询界面
        resp.sendRedirect(req.getContextPath()+"/store/company?operation=list");

    }
}
